import { ForbiddenException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from 'src/user/user.service';
import * as argon2 from 'argon2';

@Injectable()
export class AuthService {
    constructor(
        private userService:UserService, // 注入userService方法
        private jwt:JwtService   // 注入jwtService 
    ){}
    async login(username:string , password:string){

        // 1. 查询用户是否存在 
        const user = await this.userService.findByUsername(username)
        if(!user){
            throw new ForbiddenException('用户名不存在，请检查用户名和密码')
        }
        
        // 2. 验证密码是否正确
        const verityPassword = await argon2.verify(user.password , password )
        if(!verityPassword){
            throw new ForbiddenException('密码错误,请重试~');
        }
        
        // 3. 通过下发token
        const token = await this.jwt.signAsync({
            username:user.username,
            userid:user.id
        })

        // 4. token更新到user表
        try {
            await this.userService.updateToken(user.id,token)
        } catch (error) {
            console.log("token写入失败" , error);
        }
        
        return user
    }

    async register(username:string , password:string){
        const user = await this.userService.findByUsername(username)
        if(user){
            throw new ForbiddenException('用户名已被占用')
        }
        return this.userService.create({username,password})
    }
}
